// pages/petPublish/petPublish.js

const AV = require('../../utils/av-weapp.js')
const qiniuUploader = require("../../utils/qiniuUploader");
var that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images:[],
    content:'',
    petCard:"",
    petCardname:"#获取关联宠物#",
    imageUrl:"",
    num:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
        that = this;
  },

  chooseImage: function () {
    // 选择图片
    wx.chooseImage({
      count: 9 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        that.setData({
          images: that.data.images.concat(tempFilePaths)
        });
      }
    })
  },
 
  previewImage: function (e) {
    // 预览图集
    var ind = e.currentTarget.dataset.ind
    wx.previewImage({
      current: that.data.images[ind],
      urls: that.data.images
    });
  },

  delete: function (e) {
    var index = e.currentTarget.dataset.index;
    var images = that.data.images;
    images.splice(index, 1);
    that.setData({
      images: images
    });
  },

  /**
   * 获取输入内容
   */
  getContent: function (e) {
    that.setData({
      content: e.detail.value
    });
  },
  cancel:function(){
    that.setData({
      content: "",
      images:[]
    });
  },

  confirm: function (e){
    console.log(that.data.content)
    var imgurl = "";
    that.data.imageUrl = "";
    that.data.num = 0;
    if (that.data.images.length > 0) {
      for (var i = 0; i < that.data.images.length;i++){
        var weibu = that.data.images[i].split(".")[that.data.images[i].split(".").length-1]
        //console.log(weibu)
        imgurl = imgurl + "img" + new Date().getTime() + i + "." + weibu + ",";
        }
      that.data.imageUrl = imgurl.substr(0, imgurl.length-1)
      //console.log(that.data.imageUrl )
      wx.showLoading({
        title: '加载中',
      })
      that.tjxx();
    }
  },

  petCard:function(){
    wx.navigateTo({
      url: '../selectTheAssociatedPetCard/selectTheAssociatedPetCard'  //跳转页面的路径，可带参数 ？隔开，不同参数用 & 分隔；相对    路径，不需要.wxml后缀
    })
  },


  tjxx: function () {
    var arr1 = that.data.imageUrl.split(",");
    console.log(arr1[that.data.num])
    wx.request({
      url: getApp().globalData.urls + '/wxgz/media/getUploadToken',
      data: {
        fileName: arr1[that.data.num]
      },

      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // post:application/x-www-form-urlencoded,get:application/json
      },
      success: function (res) {
        var e = res;
        console.log(e.data)
        if (e.data.code == 200) {
          qiniuUploader.upload(that.data.images[that.data.num], (res) => {
            that.setData({
              'imageURL': res.imageURL,
            });
            
              that.setData({
                num: (that.data.num + 1)
              })
              console.log(that.data.num)
              if (that.data.num == that.data.images.length) {
                /**
                 * 上传完毕
                 */
                that.savePetshow();
              } else {
                that.tjxx();
              }
            
          }, (error) => {
            wx.hideLoading()
            wx.showToast({
              title: error,
            })
            console.log('error: ' + error);
          }, {
              region: 'ECN',
              key: arr1[that.data.num],
              uptoken: e.data.data, // 由其他程序生成七牛 uptoken
            }, (res) => {
              console.log('上传进度', res.progress)
             
            });
        }else{
          wx.hideLoading()
          wx.showToast({
            title: res.data.msg,
          })
        }
      },
      fail: function () {
        wx.hideLoading()
        wx.showToast({
          title: '网络问题',
        })
      }
    })
  },
  savePetshow:function(){
    wx.request({
      url: getApp().globalData.urls + '/wxgz/petshow/savePetshow',
      data: {
        token:wx.getStorageSync("token"),
        petId: that.data.petCard == "" ? "" : that.data.petCard.id,
        videoUrl:"",
        imageUrl: that.data.imageUrl,
        title: that.data.content,
      },

      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // post:application/x-www-form-urlencoded,get:application/json
      },
      success: function (res) {
        wx.hideLoading()
        console.log(res.data)
        if(res.data.code == 200){
          that.setData({
            content: "",
            images: [],
            petCard:"",
            petCardname: "#获取关联宠物#",
          });
          wx.showToast({
            title: '发表成功',
          })
        }else{
          wx.showToast({
            title: '发表失败',
          })
        }
      },
      fail:function(e){
        wx.hideLoading()
        wx.showToast({
          title: '网络问题',
        })
      }
    })
  },

})